import { memo, useEffect, useState, useRef, useCallback } from 'react';
import React from 'react';
import {
  Table,
  Button,
  Space,
  Tag,
  Input,
  Drawer,
  Form,
  Popconfirm,
  Typography,
  Card,
  Select,
  Image,
  Spin,
  App,
  Upload,
  message as antdMessage,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { UploadFile, UploadProps, RcFile } from 'antd/es/upload/interface';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import {
  getCourseListApi,
  addCourseApi,
  updateCourseApi,
  deleteCourseApi,
  uploadFileApi,
  getCourseCategoryApi,
} from '@/api/adminApi';
import Editor from '@monaco-editor/react';
import styled from 'styled-components';
import { motion } from 'framer-motion';

const { Title } = Typography;
const { Option } = Select;
const { TextArea } = Input;

// 样式组件
const StyledCard = styled(Card)`
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
    transform: translateY(-2px);
  }
`;

const AnimatedButton = styled(Button)`
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }
`;

const CourseContainer = styled.div`
  padding: 24px;
`;

const HeaderRow = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
`;

const SearchForm = styled.div`
  display: flex;
  gap: 16px;
`;

interface CourseData {
  id: string;
  name: string;
  description: string;
  image: string;
  type: string;
  category: string;
  content: string;
  video_url: string;
  created_at: string;
  updated_at: string;
}

// 检查文件类型
const isImageType = (file: RcFile) => {
  const acceptedImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
  return acceptedImageTypes.includes(file.type);
};

const isVideoType = (file: RcFile) => {
  return file.type === 'video/mp4';
};

// 上传前检查文件类型和大小
const beforeImageUpload = (file: RcFile) => {
  const isImage = isImageType(file);
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    antdMessage.error('只能上传JPG/PNG/GIF格式的图片!');
  }
  if (!isLt2M) {
    antdMessage.error('图片大小不能超过2MB!');
  }

  return isImage && isLt2M;
};

const beforeVideoUpload = (file: RcFile) => {
  const isVideo = isVideoType(file);
  const isLt100M = file.size / 1024 / 1024 < 100;

  if (!isVideo) {
    antdMessage.error('只能上传MP4格式的视频!');
  }
  if (!isLt100M) {
    antdMessage.error('视频大小不能超过100MB!');
  }

  return isVideo && isLt100M;
};

const Course = () => {
  const { message, notification } = App.useApp();
  // 课程列表
  const [courseList, setCourseList] = useState<CourseData[]>([]);
  // 加载状态
  const [loading, setLoading] = useState(false);
  // 抽屉可见状态
  const [drawerVisible, setDrawerVisible] = useState(false);
  // 编辑状态
  const [isEditing, setIsEditing] = useState(false);
  // 当前课程
  const [currentCourse, setCurrentCourse] = useState<CourseData | null>(null);
  // 搜索文本
  const [searchText, setSearchText] = useState('');
  // 表单实例
  const [form] = Form.useForm();
  // 编辑器实例
  const editorRef = useRef<any>(null);
  // 封面上传列表
  const [imageFileList, setImageFileList] = useState<UploadFile[]>([]);
  // 封面上传状态
  const [imageUploading, setImageUploading] = useState(false);
  // 视频上传状态
  const [videoFileList, setVideoFileList] = useState<UploadFile[]>([]);
  // 视频上传状态
  const [videoUploading, setVideoUploading] = useState(false);
  // 课程分类
  const [courseCategories, setCourseCategories] = useState<
    { key: string; value: string; label: string }[]
  >([]);

  // 定义可能的课程类型和分类
  const courseTypes = [
    {
      key: 'festival',
      value: 'festival',
      label: '节日',
    },
    {
      key: 'solarTerm',
      value: 'solarTerm',
      label: '二十四节气',
    },
    {
      key: 'zodiac',
      value: 'zodiac',
      label: '十二生肖',
    },
    {
      key: 'chineseZodiac',
      value: 'chineseZodiac',
      label: '星座',
    },
  ];

  // 获取课程分类
  const fetchCourseCategory = async () => {
    const res = await getCourseCategoryApi();
    if (res.code === 200) {
      setCourseCategories(res.data);
    }
  };

  // 获取课程列表
  const fetchCourseList = useCallback(async () => {
    setLoading(true);
    try {
      const res = await getCourseListApi();
      if (res.code === 200) {
        setCourseList(res.data);
        notification.success({
          message: '获取课程列表成功',
          placement: 'topRight',
          duration: 2,
        });
      } else {
        message.error(res.message || '获取课程列表失败');
      }
    } catch (error) {
      console.error('获取课程列表出错:', error);
      message.error('获取课程列表出错');
    } finally {
      setLoading(false);
    }
  }, [message, notification]);

  // 初始加载数据
  useEffect(() => {
    fetchCourseList();
    fetchCourseCategory();
  }, [fetchCourseList]);

  // 处理添加或编辑课程
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      // 获取编辑器内容
      if (editorRef.current) {
        values.content = editorRef.current.getValue();
      }

      setLoading(true);

      if (isEditing && currentCourse) {
        // 更新课程
        const updateData = {
          id: currentCourse.id,
          ...values,
        };

        const res = await updateCourseApi(updateData);
        if (res.code === 200) {
          message.success('更新课程成功');
          setDrawerVisible(false);
          fetchCourseList();
        } else {
          message.error(res.message || '更新课程失败');
        }
      } else {
        // 添加新课程
        const res = await addCourseApi(values);
        if (res.code === 200) {
          message.success('添加课程成功');
          setDrawerVisible(false);
          fetchCourseList();
        } else {
          message.error(res.message || '添加课程失败');
        }
      }
    } catch (error) {
      console.error('表单验证失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 处理删除课程
  const handleDelete = async (id: string) => {
    setLoading(true);
    try {
      const res = await deleteCourseApi(id);
      if (res.code === 200) {
        message.success('删除课程成功');
        fetchCourseList();
      } else {
        message.error(res.message || '删除课程失败');
      }
    } catch (error) {
      console.error('删除课程出错:', error);
      message.error('删除课程出错');
    } finally {
      setLoading(false);
    }
  };

  // 打开抽屉以编辑课程
  const handleEdit = (record: CourseData) => {
    setCurrentCourse(record);
    setIsEditing(true);
    form.setFieldsValue({
      name: record.name,
      description: record.description,
      type: record.type,
      category: record.category,
      video_url: record.video_url,
      image: record.image,
      content: record.content,
    });
    setVideoFileList([]);

    // 设置图片文件列表
    if (record.image) {
      setImageFileList([
        {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: record.image,
        },
      ]);
    } else {
      setImageFileList([]);
    }

    // 设置视频文件列表
    if (record.video_url) {
      setVideoFileList([
        {
          uid: '-1',
          name: 'video.mp4',
          status: 'done',
          url: record.video_url,
        },
      ]);
    } else {
      setVideoFileList([]);
    }

    setDrawerVisible(true);
  };

  // 打开抽屉以添加新课程
  const handleAdd = () => {
    setCurrentCourse(null);
    setIsEditing(false);
    form.resetFields();
    setImageFileList([]);
    setVideoFileList([]);
    setDrawerVisible(true);
  };

  // 关闭抽屉
  const handleDrawerClose = () => {
    setDrawerVisible(false);
  };

  // 处理图片上传
  const handleImageUpload: UploadProps['customRequest'] = async (options) => {
    const { onSuccess, onError, file } = options;

    setImageUploading(true);

    try {
      const formData = new FormData();
      formData.append('img', file as Blob);

      const res = await uploadFileApi(formData);

      if (res.code === 200) {
        message.success('图片上传成功');
        onSuccess?.(res.data);
        form.setFieldsValue({ image: res.data });
      } else {
        message.error(res.message || '图片上传失败');
        onError?.(new Error('上传失败'));
      }
    } catch (error) {
      console.error('图片上传出错:', error);
      message.error('图片上传出错');
      onError?.(error as Error);
    } finally {
      setImageUploading(false);
    }
  };

  // 处理视频上传
  const handleVideoUpload: UploadProps['customRequest'] = async (options) => {
    const { onSuccess, onError, file } = options;

    setVideoUploading(true);

    try {
      const formData = new FormData();
      formData.append('img', file as Blob);

      const res = await uploadFileApi(formData);

      if (res.code === 200) {
        message.success('视频上传成功');
        // 设置文件URL
        const fileObj = file as any;
        fileObj.url = res.data;
        // 更新到表单
        form.setFieldsValue({ video_url: res.data });
        // 更新视频列表
        setVideoFileList([
          {
            uid: fileObj.uid || `-${Date.now()}`,
            name: fileObj.name || '视频文件',
            status: 'done',
            url: res.data,
            type: fileObj.type || 'video/mp4',
            size: fileObj.size || 0,
          } as UploadFile,
        ]);
        onSuccess?.(res.data);
      } else {
        message.error(res.message || '视频上传失败');
        onError?.(new Error('上传失败'));
      }
    } catch (error) {
      console.error('视频上传出错:', error);
      message.error('视频上传出错');
      onError?.(error as Error);
    } finally {
      setVideoUploading(false);
    }
  };

  // 图片上传组件
  const uploadImageProps: UploadProps = {
    listType: 'picture-card',
    fileList: imageFileList,
    beforeUpload: beforeImageUpload,
    customRequest: handleImageUpload,
    onChange: ({ fileList }) => {
      setImageFileList(fileList);
    },
    onRemove: () => {
      form.setFieldsValue({ image: '' });
      setImageFileList([]);
    },
    accept: 'image/jpeg,image/png,image/gif,image/jpg',
  };

  // 视频上传组件
  const uploadVideoProps: UploadProps = {
    listType: 'picture-card',
    fileList: videoFileList,
    beforeUpload: beforeVideoUpload,
    customRequest: handleVideoUpload,
    onRemove: () => {
      form.setFieldsValue({ video_url: '' });
      setVideoFileList([]);
    },
    accept: 'video/mp4',
    onChange: (info) => {
      // 处理文件状态变化
      if (info.file.status === 'done') {
        // 文件上传完成，自定义上传逻辑已经处理
        console.log('文件上传完成', info.file);
      } else if (info.file.status === 'error') {
        // 上传失败
        message.error(`${info.file.name} 上传失败`);
        setVideoFileList([]);
      } else if (info.file.status === 'uploading') {
        // 上传中状态由setVideoUploading控制
        console.log('文件上传中', info.file);
      } else if (info.file.status === 'removed') {
        // 文件被移除，由onRemove处理
        console.log('文件被移除', info.file);
      }
    },
  };

  // 表格列定义
  const columns: ColumnsType<CourseData> = [
    {
      title: '课程名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => <a>{text}</a>,
    },
    {
      title: '封面',
      dataIndex: 'image',
      key: 'image',
      width: 100,
      render: (image: string) => (
        <Image
          src={image}
          alt="课程封面"
          width={80}
          height={45}
          style={{ objectFit: 'cover', borderRadius: '4px' }}
          placeholder={
            <div
              style={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                width: '100%',
                height: '100%',
                background: '#f5f5f5',
              }}
            >
              <Spin size="small" />
            </div>
          }
        />
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => (
        <Tag color={'purple'}>{courseTypes.find((item) => item.value === type)?.label}</Tag>
      ),
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category: string) => (
        <Tag color={'blue'}>{courseCategories.find((item) => item.value === category)?.label}</Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date: string) => new Date(date).toLocaleString('zh-CN'),
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      render: (date: string) => new Date(date).toLocaleString('zh-CN'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: CourseData) => (
        <Space size="middle">
          <AnimatedButton
            type="primary"
            icon={<EditOutlined />}
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </AnimatedButton>
          <Popconfirm
            title="确定删除该课程吗?"
            description="删除后无法恢复，请谨慎操作"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <AnimatedButton
              danger
              icon={<DeleteOutlined />}
              size="small"
            >
              删除
            </AnimatedButton>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理Monaco编辑器的初始化
  const handleEditorDidMount = (editor: any) => {
    editorRef.current = editor;
    // 如果是编辑模式，设置初始内容
    if (isEditing && currentCourse) {
      editor.setValue(currentCourse.content || '');
    }
  };

  // 过滤表格数据
  const filteredData = courseList.filter((item) => {
    return (
      item.name.toLowerCase().includes(searchText.toLowerCase()) ||
      item.description.toLowerCase().includes(searchText.toLowerCase()) ||
      item.type.toLowerCase().includes(searchText.toLowerCase()) ||
      item.category.toLowerCase().includes(searchText.toLowerCase())
    );
  });

  // 渲染抽屉表单内容
  const renderDrawerContent = () => {
    return (
      <>
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="课程名称"
            rules={[
              { required: true, message: '请输入课程名称' },
              { min: 2, max: 15, message: '课程名称不能超过15个字' },
            ]}
          >
            <Input
              placeholder="请输入课程名称"
              showCount
              maxLength={15}
            />
          </Form.Item>

          <Form.Item
            name="description"
            label="课程简介"
            rules={[
              { required: true, message: '请输入课程简介' },
              { min: 2, max: 100, message: '课程简介不能超过100个字' },
            ]}
          >
            <TextArea
              rows={4}
              placeholder="请输入课程简介"
              showCount
              maxLength={100}
            />
          </Form.Item>

          <Form.Item
            name="image"
            label="课程封面"
            rules={[{ required: true, message: '请上传课程封面' }]}
            extra="支持JPG/PNG/GIF格式，大小不超过2MB"
          >
            <Upload {...uploadImageProps}>
              {imageFileList.length >= 1 ? null : (
                <div>
                  {imageUploading ? <Spin /> : <PlusOutlined />}
                  <div style={{ marginTop: 8 }}>上传封面</div>
                </div>
              )}
            </Upload>
          </Form.Item>

          <Form.Item
            name="type"
            label="课程类型"
            rules={[{ required: true, message: '请选择课程类型' }]}
          >
            <Select placeholder="请选择课程类型">
              {courseTypes.map((type) => (
                <Option
                  key={type.key}
                  value={type.value}
                >
                  {type.label}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="category"
            label="课程分类"
            rules={[{ required: true, message: '请选择课程分类' }]}
          >
            <Select
              placeholder="请选择课程分类"
              showSearch
              filterOption={(input, option) => {
                console.log(input, option);
                return (option?.children as any).toLowerCase().includes(input.toLowerCase());
              }}
            >
              {courseCategories.map((category) => (
                <Option
                  key={category.key}
                  value={category.value}
                >
                  {category.label}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="video_url"
            label="课程视频"
            rules={[{ required: true, message: '请上传课程视频' }]}
            extra="仅支持MP4格式，大小不超过100MB"
          >
            <div
              style={{
                width: '50%',
                position: 'relative',
                borderRadius: 8,
                overflow: 'hidden',
                backgroundColor: '#f7f7f7',
                border: '1px solid #d9d9d9',
                transition: 'all 0.3s',
              }}
            >
              {/* 16:9 宽高比容器 */}
              <div
                style={{
                  paddingTop: '56.25%' /* 16:9 宽高比 */,
                  position: 'relative',
                }}
              >
                {videoFileList.length === 0 ? (
                  // 上传组件
                  <div
                    style={{
                      position: 'absolute',
                      top: 0,
                      left: 0,
                      width: '100%',
                      height: '100%',
                      display: 'flex',
                      flexDirection: 'column',
                      justifyContent: 'center',
                      alignItems: 'center',
                      background: '#fafafa',
                      border: '1px dashed #d9d9d9',
                      borderRadius: 8,
                      cursor: 'pointer',
                      transition: 'border-color 0.3s',
                    }}
                    onClick={() => {
                      // 触发上传组件的点击事件
                      const uploadBtn = document.querySelector(
                        '.video-upload-btn button'
                      ) as HTMLElement;
                      if (uploadBtn) uploadBtn.click();
                    }}
                  >
                    {videoUploading ? (
                      // 上传中状态
                      <div style={{ textAlign: 'center' }}>
                        <Spin size="large" />
                        <div style={{ marginTop: 16, color: '#1890ff' }}>视频上传中...</div>
                      </div>
                    ) : (
                      // 默认状态
                      <>
                        <PlusOutlined style={{ fontSize: 24, color: '#1890ff', marginBottom: 8 }} />
                        <div style={{ color: '#666' }}>上传视频</div>
                      </>
                    )}
                    {/* 隐藏实际的上传组件但保持功能 */}
                    <div
                      className="video-upload-btn"
                      style={{ display: 'none' }}
                    >
                      <Upload {...uploadVideoProps}>
                        <Button>上传</Button>
                      </Upload>
                    </div>
                  </div>
                ) : (
                  // 视频播放器
                  <div
                    style={{
                      position: 'absolute',
                      top: 0,
                      left: 0,
                      width: '100%',
                      height: '100%',
                      display: 'flex',
                      justifyContent: 'center',
                      alignItems: 'center',
                      background: '#000',
                    }}
                  >
                    <video
                      src={videoFileList[0].url}
                      style={{
                        width: '100%',
                        height: '100%',
                        objectFit: 'contain',
                      }}
                      controls
                      preload="metadata"
                      poster={videoFileList[0].thumbUrl}
                    />

                    {/* 删除按钮 */}
                    <Button
                      type="primary"
                      danger
                      icon={<DeleteOutlined />}
                      size="small"
                      style={{
                        position: 'absolute',
                        top: 8,
                        right: 8,
                        opacity: 0.8,
                        transition: 'opacity 0.3s',
                      }}
                      onClick={() => {
                        // 删除视频
                        form.setFieldsValue({ video_url: '' });
                        setVideoFileList([]);
                      }}
                      onMouseOver={(e) => {
                        e.currentTarget.style.opacity = '1';
                      }}
                      onMouseOut={(e) => {
                        e.currentTarget.style.opacity = '0.8';
                      }}
                    >
                      删除视频
                    </Button>
                  </div>
                )}
              </div>
            </div>

            {/* 视频信息 */}
            {videoFileList.length > 0 && videoFileList[0].url && (
              <div
                style={{
                  marginTop: 8,
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                }}
              >
                <Tag color="blue">{videoFileList[0].name || '已上传视频'}</Tag>
              </div>
            )}
          </Form.Item>

          <Form.Item
            label="课程内容"
            required
          >
            <div style={{ border: '1px solid #d9d9d9', borderRadius: '2px' }}>
              <Editor
                height="500px"
                defaultLanguage="markdown"
                defaultValue={
                  isEditing && currentCourse
                    ? currentCourse.content
                    : '# 开始编辑课程内容\n\n请在此处编写课程内容，支持Markdown格式。'
                }
                theme="vs-light"
                onMount={handleEditorDidMount}
                options={{
                  minimap: { enabled: false },
                  scrollBeyondLastLine: false,
                  wordWrap: 'on',
                }}
              />
            </div>
          </Form.Item>
        </Form>
      </>
    );
  };

  return (
    <CourseContainer>
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
      >
        <StyledCard>
          <HeaderRow>
            <Title level={4}>课程管理</Title>
            <SearchForm>
              <Input
                placeholder="搜索课程..."
                prefix={<SearchOutlined />}
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                style={{ width: 250 }}
                allowClear
              />
              <AnimatedButton
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                新增课程
              </AnimatedButton>
            </SearchForm>
          </HeaderRow>

          <Table
            columns={columns}
            dataSource={filteredData}
            rowKey="id"
            loading={loading}
            pagination={{
              pageSize: 8,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
            }}
            bordered
            size="middle"
            components={{
              body: {
                row: (props) => (
                  <motion.tr
                    {...props}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ duration: 0.3 }}
                    whileHover={{
                      backgroundColor: 'rgba(0, 0, 0, 0.02)',
                      transition: { duration: 0.2 },
                    }}
                  />
                ),
              },
            }}
          />
        </StyledCard>
      </motion.div>

      <Drawer
        title={isEditing ? '编辑课程' : '新增课程'}
        placement="right"
        width={720}
        onClose={handleDrawerClose}
        open={drawerVisible}
        extra={
          <Space>
            <Button onClick={handleDrawerClose}>取消</Button>
            <Button
              type="primary"
              onClick={handleSubmit}
              loading={loading}
            >
              提交
            </Button>
          </Space>
        }
      >
        {renderDrawerContent()}
      </Drawer>
    </CourseContainer>
  );
};

export default memo(Course);
